package servlet;

import dao.UserDao;
import entity.User;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload.do")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    private static final long serialVersionUID = 2L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");
        Collection<Part> collection = request.getParts();
        Iterator<Part> iter = collection.iterator();
        StringBuilder sb = new StringBuilder();
        while(iter.hasNext()) {
            Part part = iter.next();
            String partName = part.getName();
            System.out.println(partName + "," + part.getSize() + "," + part.getContentType());
            String fileName = getFileName(part);
            if (fileName == null) continue;
            System.out.println("文件名：" + fileName);
            part.write("d:/tmp/img/" + fileName);
            if (sb.length() != 0) sb.append(", ");
            sb.append("http://localhost:8080" + request.getContextPath() + "/download.do?f=" + fileName);
        }
        UserDao userDao = new UserDao();
        User user = (User) request.getSession().getAttribute("user");
        int ret = userDao.update_img(user,sb.toString());
        if(ret == -1) {
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
        user.setHeadimg(sb.toString());
        request.getSession().setAttribute("user", user);
        request.getRequestDispatcher("main.jsp").forward(request, response);

    }

    public String getFileName(Part part) {
        if (part.getSize() == 0 || part.getContentType() == null) return null;
        String header = part.getHeader("Content-Disposition");//获得Content-Disposition的头信息
        int idx = header.lastIndexOf("filename=\"");//获取filename=“字符串的开始下标
        String fileName = header.substring(idx+"filename=\"".length(), header.length()-1);
        return fileName;
    }
}